home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 10215 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: HELP: Floating point precision
  5. Date: Sat, 16 Mar 96 00:25:57 GMT
  6. Organization: none
  7. Message-ID: <826935957snz@genesis.demon.co.uk>
  8. References: <3140831B.1597@interport.com>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: relay-4.mail.demon.net!post.demon.co.uk!genesis.demon.co.uk
  13.  
  14. In article <3140831B.1597@interport.com> jeremy@interport.com "jeremy" writes:
  15.  
  16. >The mechanism for casting 4-byte float to 8-byte double is 
  17. >causing me some problems. The following code:
  18. >
  19. >        float f;
  20. >        double d;
  21. >        f = 1.332;
  22. >        d = (double) f;
  23. >
  24. >results in:
  25. >
  26. >f = 1.33200
  27. >d = 1.3320000171661
  28. >
  29. >(I am using Microsoft Visual C++ 2.1 compiler).
  30. >
  31. >I understand that this is due to complexities in 
  32. >floating-point storage beyond my ken. Is there any run-time 
  33. >library function which would cast f to 1.3320000000000 ? If not, 
  34. >does anyone know how to write such a function? Using a lot of 
  35. >processor cycles is not a big issue in the place I am having 
  36. >this problem; I could afford to waste a little time.
  37.  
  38. You could start with something like:
  39.  
  40.           d = floor(f * x + 0.5) / x;
  41.  
  42. where x is a double quantity that is a power of 10 and determines the number
  43. of decimal places you want to keep (e.g. 1000.0 here for 3dp or 100000.0 for
  44. 5 dp). If f is negative you would need to use ceil() instead of floor().
  45.  
  46. -- 
  47. -----------------------------------------
  48. Lawrence Kirby | fred@genesis.demon.co.uk
  49. Wilts, England | 70734.126@compuserve.com
  50. -----------------------------------------
  51.